package com.woniu.pay.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.woniu.entity.Result;
import com.woniu.pay.entity.PayObject;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

@RestController
@RequestMapping("/alipay")
@Api(tags = "支付管理")
public class AlipayController {

    @PostMapping("/toPay")
    @ApiOperation("支付宝沙箱支付")
    public Result toPay(@RequestBody PayObject payObject){
        AlipayClient alipayClient = new DefaultAlipayClient(
                "https://openapi.alipaydev.com/gateway.do",
                "2021000121695536",
                "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDD08qNg9JYJowkYMvK6xDOlV7TNPu+TZjdMH7ZRp9J8jNUBQBov/JqPyIqSh4FrM0teXU9BH3hedenfjZVMXl4ckfaMXIKDtPCFw/TWfH5cb3sKgOCLgMPWo8hX2hgAqJOl7ckulwN+Iqrt36d55W3ZId+y3m640xrDupPHv+p+rxPjC5l8vQw2pGeXgVkj1XCMmTVzNt+/0Su8CJJ7PhXYMN2shurkJBirbVPbMMjeT2nk3MKMsqelDaztzja87k8yxBxHp2MlmoaqtuN5brgDfnz5VlKD0NJSIdayH2xa+DO5uCLTaFc1ESQqmvAOyupBY6GxSo+7ZmNDJD6l8oZAgMBAAECggEAAjeVpYCGkyTslUTbSdLbf9tFFZMV/pOWVXrFFOStzQKG/j6IQKdbsURBuMTaDipksE0dvLEeU70zadwN9Wz3+RsiISBKMD72us3UCgqMqMxW4COhoomu0y+tSy1vWxbsi4NAOZQ6kpXrzAHp1xPWKBtlRVQ8bpdAOD4U/QxWzK/a+/w49olgE8G4Lkz6Uf6yQi0zbbiS6t2MTLt9O+xqDgX5CXnOQWD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chKQb62L1iSRZC30od7Fu+aGDOO0E22td2FyBVW1gtk1AfIEZ0eNyQvL/F8Rwruz/M9gGGLU37WlNOKvLLL9L+ZxZGA3d82pIsmn6R3A1EFCC9A1Nf5sV9JAaJzJfBznYKayHRyqlPmcQCRVQkl4q31XMdlk5iDKkAbwct/t9MiK8+f/ZHaNMctMNgVtwmGG/rJElunnncJQQpH+Havex6RX49ccPYFYlXH5ugK8xmfBK4xG/F/3UbgkrOQd3f7R5Jufu3wI3lI9UzqZdJ59srQSXvSNQNgrWy5WEI+c3bWW5Iqq1nxWgSnxRJ2/q2Teqcsf2HY5qD64QIDAQAB", "RSA2");  //获得初始化的AlipayClient
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest(); //创建API对应的request
        alipayRequest.setReturnUrl("https://116013uc88.yicp.fun/order/return_url");//同步回调
        alipayRequest.setNotifyUrl("https://116013uc88.yicp.fun/order/notify_url"); //在公共参数中设置回跳和通知地址//异步回调
        alipayRequest.setBizContent("{" +
                "    \"out_trade_no\":"+payObject.getOutTradeNo()+"," +
                "    \"product_code\":\"FAST_INSTANT_TRADE_PAY\"," +
                "    \"total_amount\":"+payObject.getTotalAmount()+"," +
                "    \"subject\":\"Iphone6 16G\"," +
                "    \"body\":\"Iphone6 16G\"," +
                "    \"passback_params\":\"merchantBizType%3d3C%26merchantBizNo%3d2016010101111\"," +
                "    \"extend_params\":{" +
                "    \"sys_service_provider_id\":\"2088511833207846\"" +
                "    }" +
                "  }"); //填充业务参数
        String form = "";
        try {
            form = alipayClient.pageExecute(alipayRequest).getBody();  //调用SDK生成表单
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }

        return Result.ok(form);
    }

    @RequestMapping("/return_url")
    public String ReturnUrl(){
        System.out.println("=============支付宝的同步回来了");
        return "index";//返回到首页
    }

    @RequestMapping("/notify_url")
    @ResponseBody
    public String notifyUrl(HttpServletRequest request){
        System.out.println("=============支付宝的异步回来了========================");

        //获取支付宝POST过来反馈信息
        Map<String,String> params = new HashMap<>();
        Map requestParams = request.getParameterMap();
        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用。
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }
        System.out.println(params);
        //切记alipaypublickey是支付宝的公钥，请去open.alipay.com对应应用下查看。
        //boolean AlipaySignature.rsaCheckV1(Map<String, String> params, String publicKey, String charset, String sign_type)
        try {
            boolean flag = AlipaySignature.rsaCheckV1(params, "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAw9PKjYPSWCaMJGDLyusQzpVe0zT7vk2Y3TB+2UafSfIzVAUAaL/yaj8iKkoeBazNLXl1PQR94XnXp342VTF5eHJH2jFyCg7TwhcP01nx+XG97CoDgi4DD1qPIV9oYAKiTpe3JLpcDfiKq7d+neeVt2SHfst5uuNMaw7qTx7/qfq8T4wuZfL0MNqRnl4FZI9VwjJk1czbfv9ErvAiSez4V2DDdrIbq5CQYq21T2zDI3k9p5NzCjLKnpQ2s7c42vO5PMsQcR6djJZqGqrbjeW64A358+VZSg9DSUiHWsh9sWvgzubgi02hXNREkKprwDsrqQWOhsUqPu2ZjQyQ+pfKGQIDAQAB", "UTF-8","RSA2");
            //如果验签失败
            if(!flag){
                return "fail";
            }
            //验签成功后
            //商户的业务逻辑  比如修改订单号
            System.out.println("修改订单成功");
            //获取订单号
            String out_trade_no = params.get("out_trade_no");// 获取本系统的订单编号
            String trade_no = params.get("trade_no");// 支付宝的交易流水号

            //更新订单数据


        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return "success";
    }
}